let mysql = require('mysql')
let md5 = require('md5')

let pool = mysql.createPool({
  connectionLimit: 10,
  host: '122.152.194.171',
  user: 'root',
  password: '123456',
  database: 'fast_rent_house'
});

// 存储聊天记录
let storeChat = (chat) => {
  return new Promise((resolve, reject) => {
    pool.query({
      sql: 'insert into chat (from_memberId, to_memberId, content, send_time) values (?,?,?,?)',
      values: [chat.uid, chat.to, chat.content, chat.time]
    }, (error, results, filed) => {
      if (error) {
        reject(error)
        return
      }
      resolve()
    })
  })
}

// 获取聊天列表
let getRecord = (chat) => {
  return new Promise((resolve, reject) => {
    pool.query({
      sql: 'select * from conversation where from_memberId=? and to_memberId=?',
      values: [chat.uid, chat.to]
    }, (error, results, filed) => {
      if (error || !results.length) {
        reject(error)
        return
      }
      resolve(results[0])
    })
  })
}

// 存储聊天列表
let storeRecord = (chat) => {
  return new Promise((resolve, reject) => {
    pool.query({
      sql: 'insert into conversation (from_memberId, to_memberId, last_chatId, unReadNum) values (?,?,?,?)',
      values: [chat.uid, chat.to, chat.room, chat.unRead]
    }, (error, results, filed) => {
      if (error) {
        reject(error)
        return
      }
      resolve(results)
    })
  })
}

// 更新聊天列表
let updateRecord = (chat) => {
  return new Promise((resolve, reject) => {
    pool.query({
      sql: 'update conversation set unReadNum=? where id=?',
      values: [chat.unRead, chat.id]
    }, (error, results, filed) => {
      if (error) {
        reject(error)
        return
      }
      resolve(results)
    })
  })
}


module.exports = {
  login({username, password}) {
    return new Promise((resolve, reject) => {
      password += ''
      pool.query({
        sql: 'select * from member_auths where `identifier`=? and `credential`=?',
        values: [username, md5(password)]
      }, (error, results, field) => {
        if (error || !results.length) {
          reject(error)
          return
        }
        resolve(results[0])
      })
    })
  },
  // 获取最近聊天记录
  getChat({uid, to, group, page}) {
    page = page || '0'
    group = group || 5
    return new Promise((resolve, reject) => {
      pool.query({
        sql: 'select * from chat where `to_memberId`=? and `from_memberId`=? and `show_status`=3 order by send_time desc limit ?, ?',
        values: [uid, to, page * group, (page + 1) * group]
      }, (error, results, field) => {
        if (error) {
          reject(error)
          return
        }
        resolve(results || [])
      })
    })
  },
  store({uid, to, content, room}) {
    let chat = {
      uid,
      to,
      content,
      time: new Date().toString()
    }
    return new Promise((resolve, reject) => {
      storeChat(chat).then(() => {
        getRecord(chat).then(result => {
          chat.id = result.id
          chat.unRead = result.unReadNum + 1
          updateRecord(chat).then(rs => resolve(rs)).catch(error => reject(error))
        }).catch((error) => {
          chat.unRead = 1
          chat.room = room
          storeRecord(chat).then(rs => resolve(rs)).catch(error => reject(error))
        })
      }).catch(error => reject(error))
    })
  }
}